﻿using System;
using System.Text.RegularExpressions;

namespace Rules
{
    public class RegexRule : RuleBase<string>
    {
        public RegexRule(Regex regex, string propertyName)
            : base(propertyName)
        {
            Regex = regex;
        }

        public RegexRule(Regex regex, string propertyName, string description)
            : base(propertyName, description)
        {
            Regex = regex;
        }

        public RegexRule(string pattern, string propertyName)
            : base(propertyName)
        {
            Regex = new Regex(pattern);
        }

        public RegexRule(string pattern, string propertyName, string description)
            : base(propertyName, description)
        {
            Regex = new Regex(pattern);
        }

        private Regex _regex;
        public Regex Regex
        {
            get { return _regex; }
            private set
            {
                if (value == null)
                    throw new ArgumentNullException("regex");
                _regex = value;
            }
        }

        protected override bool DoEvaluate(string subject)
        {
            if (subject == null)
                return true;
            else
                return this.Regex.IsMatch(subject);
        }

        protected override string GetDefaultDescription()
        {
            return string.Format("{0} must be in a valid format", PropertyName);
        }
    }
}
